<template>
    <div
        class="nimble-contnair"
        v-loading="isLoading"
        element-loading-background="rgba(250, 250, 250, 0.7)"
    >
        <!-- 灵活分期 -->
        <!-- <el-card
      shadow="never"
      v-loading="isLoading"
      element-loading-background="rgba(250, 250, 250, 0.7)"
    >
      <div slot="headerss" class="clearfix">
        <span>灵活分期</span>
        <el-button style="float: right; padding: 3px 20px;" type="text" @click="showTrial=false">关 闭</el-button>
        </div>-->
        <cardComponent pageTitle="灵活分期">
            <template slot="cardBody">
                <el-form ref="form" :model="nimbleForm" label-width="120px" size="small">
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="账户类别 : ">
                                <el-input
                                    disabled
                                    v-model="nimbleForm.CATEGORY"
                                    style="width: 100%; border: none"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="主卡卡号 : ">
                                <el-input
                                    disabled
                                    v-model="nimbleForm.CARDNBR"
                                    style="width: 100%;"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7">
                            <el-form-item label="手续收取方式 : ">
                                <el-select
                                    v-model="nimbleForm.CREDNO"
                                    placeholder="请选择手续收取方式"
                                    style="width: 100%;"
                                >
                                    <el-option label="一次性收取" value="0001"></el-option>
                                    <el-option label="分期收取" value="0011"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-form-item size="large" label-width="0">
                        <!-- 3076 -->
                        <el-button type="primary" size="small" @click="qry">查 询</el-button>
                        <el-button type="primary" size="small" plain @click="onShortcut">未出账单查询</el-button>
                        <el-button
                            type="primary"
                            size="small"
                            plain
                            @click="onMptransQuery"
                        >分期付款交易明细查询</el-button>
                    </el-form-item>
                </el-form>
                <!-- </el-card> -->

                <!-- 灵活分期查询结果窗口 -->
                <el-card shadow="never" v-if="showNimble00">
                    <div slot="headerss" class="clearfix">
                        <span>灵活分期查询</span>
                        <el-button
                            style="float: right; padding: 3px 20px;"
                            type="text"
                            @click="showNimble00=false"
                        >关 闭</el-button>
                    </div>
                    <div>
                        <el-table
                            :data="tableData"
                            border
                            stripe
                            style="width: 100%;"
                            highlight-current-row
                            @current-change="handleCurrentChange"
                            class="heard-bg business_table"
                        >
                            <el-table-column label="人民币列表 ( 当前账户： 个人卡账户 )">
                                <el-table-column width="36">
                                    <template slot-scope="scope">
                                        <el-radio v-model="id" :label="scope.row.i">{{" "}}</el-radio>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="PURTIME_1" label="交易日期" min-width="180"></el-table-column>
                                <el-table-column prop="PURDATE_1" label="记账日期" min-width="120"></el-table-column>
                                <el-table-column prop="AMOUNT" label="交易金额" min-width="120"></el-table-column>
                                <el-table-column prop="TRANTYPE" label="交易类型" min-width="120"></el-table-column>
                                <el-table-column prop="CARDEND" label="卡号末四位" min-width="120"></el-table-column>
                                <el-table-column prop="DESLINE1" label="交易描述" min-width="120"></el-table-column>
                                <el-table-column prop="MPFLAG_1" label="灵活分期标志" min-width="120"></el-table-column>
                                <el-table-column prop="NBRMTHS" label="灵活分期期数"></el-table-column>
                            </el-table-column>
                        </el-table>
                        <el-divider content-position="center">费用试算表</el-divider>

                        <el-table
                            :data="tryData"
                            border
                            stripe
                            class="heard-bg business_table"
                            style="width: 100%;"
                            size="small"
                        >
                            <el-table-column prop="OUTFLAG" label="选择分期期数">
                                <template slot-scope="scope">
                                    <el-select
                                        v-model="scope.row.OUTFLAG"
                                        style="width: 100%;"
                                        placeholder="选择分期期数"
                                        @change="onChanger"
                                    >
                                        <el-option
                                            v-for="(item, index) in instalmentNoList"
                                            :key="index"
                                            :label="item.label"
                                            :value="item.nbrMths"
                                        ></el-option>
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column prop="CORPUS" label="首期还款额"></el-table-column>
                            <el-table-column prop="REMONTHFEE" label="每期分摊本金"></el-table-column>
                            <el-table-column prop="ALLMONTHSFEE" label="分期总手续费"></el-table-column>
                            <el-table-column prop="ALLCOUNTFEE" label="本金+手续费总计"></el-table-column>
                            <el-table-column prop="MPIRR" label="年化利率"></el-table-column>
                        </el-table>
                        <div class="footer">
                            <el-button
                                type="primary"
                                size="small"
                                @click="onChoice"
                                v-preventReClick
                            >申 请</el-button>
                            <el-button
                                :disabled="currentPageIndex <= 0"
                                type="primary"
                                size="small"
                                @click="handleChangePage('pre')"
                            >上一页</el-button>
                            <el-button
                                :disabled="nextButtonFlag"
                                type="primary"
                                size="small"
                                @click="handleChangePage('next')"
                            >下一页</el-button>
                            <!-- <el-button size="small" @click="showTrial = false">关闭</el-button> -->
                        </div>
                    </div>
                </el-card>

                <!-- 未出账单明细查询结果窗口 -->
                <el-card shadow="never" v-if="showNimble01">
                    <div slot="headerss" class="clearfix">
                        <span>未出账单明细查询</span>
                        <el-button
                            style="float: right; padding: 3px 20px;"
                            type="text"
                            @click="showTrial=false"
                        >关 闭</el-button>
                    </div>
                    <div></div>
                </el-card>

                <!-- 分期付款交易明细查询结果窗口 -->
                <el-card shadow="never" v-if="showNimble02">
                    <div slot="headerss" class="clearfix">
                        <span>分期付款交易明细查询</span>
                    </div>
                    <div></div>
                </el-card>

                <!-- 申请成功返回提示 -->
                <ConfirmWindow
                    v-if="showApplydaily"
                    @isShow="close"
                    :dataList="ApplyCashForm"
                    :title="'灵活 信用计划申请成功, 请勿重复申请 ！ '"
                />
            </template>
        </cardComponent>
    </div>
</template>

<script>
import { mapState } from 'vuex';
import moment from 'moment';
import cardComponent from '@/components/cardComponent/cardComponent.vue';
import {
    getInstalmentList, myMoment, getFormatDate, getDictMappingValue,
} from '@/utils/Common';
import { get_4xxx, get_3xxx } from '@/apis/getAPIClass';
import ConfirmWindow from '@/components/ConfirmWindow/ConfirmWindow.vue';
import { setNumber, ChangePage, tbBudgetRequisi } from '@/utils/Object';

export default {
    name: 'nimble',
    data() {
        return {
            nimbleForm: {
                CATEGORY: '',
                CARDNBR: '',
                CREDNO: '0001',
            },
            tableData: [
                {
                    CURRNUM: '156', // 货币代码 156")人民币 "840")美元
                },
            ],
            ApplyCashForm: [],
            showNimble00: false,
            showNimble01: false,
            showApplydaily: false,
            showNimble02: false,
            isLoading: false,
            currentRow: null,
            id: '',
            pagingDataList: [], // 翻页上送字段列表
            currentPageIndex: 0, // 当前页,
            nextButtonFlag: true, // 下翻页按钮 显示控制阀
            MPNO: '0', // 翻页分期付款序号首次查询时送起始序号，默认为0 下翻页查询时上送上次查询结果的最后一条记录返回的交易序号
            RTNIND: '', // 首次查询上送空； 下翻页查询上送1；
            BEGYM: '00000000',
            VALDATE: '',
            PURDATE: '',
            PURTIME: '',
            TRANNO: '',
            tryData: [
                {
                    OUTFLAG: '3',
                    CORPUS: 0,
                    REMONTHFEE: 0,
                    ALLMONTHSFEE: 0,
                    ALLCOUNTFEE: 0,
                    MPIRR: 0,
                },
            ],
            instalmentNoList: [],
        };
    },
    name: 'nimble',
    components: {
        cardComponent,
        ConfirmWindow,
    },
    async mounted() {
        // 获取账户类别
        const MY_CATEGORY = await getDictMappingValue('CATE', this.cardInfo_3004.CATEGORY, this) || this.cardInfo_3004.CATEGORY;

        this.nimbleForm.CATEGORY = MY_CATEGORY;

        this.onLoadNimbleOBJ();
    },
    computed: mapState({
        defaultParams: state => state.common.defaultParams, // 接口默认参数
        cardInfo_3004: state => state.common.cardInfo_3004,
        cardList_3601: state => state.common.cardList_3601,
        pinFlag: state => state.common.pinFlag, // 是否密码检查标志
    }),
    methods: {
        async onLoadNimbleOBJ() {
            this.nimbleForm.CARDNBR = this.cardInfo_3004.CARDNO;

            // 分期期数
            this.instalmentNoList = await getInstalmentList('2002', this);
            console.log(this.instalmentNoList);
            // this.nimbleForm.CATEGORY = this.cardInfo_3004.CATEGORY;
        },
        // 3076 可灵活分期付款的交易明细查询
        async qry() {
            this.isLoading = true;
            this.RTNIND = '';
            this.currentRow = null;
            this.pagingDataList = [];
            this.id = '';
            this.VALDATE = '';
            this.PURDATE = '';
            this.PURTIME = '';
            this.TRANNO = '';
            this.RTNIND = '';
            this.BEGYM = '00000000';
            this.tryData = [
                {
                    OUTFLAG: '3',
                    CORPUS: 0,
                    REMONTHFEE: 0,
                    ALLMONTHSFEE: 0,
                    ALLCOUNTFEE: 0,
                    MPIRR: 0,
                },
            ];
            this.RTNIND = '';

            this.get_3076();
        },
        async get_3076() {
            // 3076 配置请求头
            const appBody_3076 = {
                CARDNBR: this.nimbleForm.CARDNBR,
                CREDNO: this.nimbleForm.CREDNO,
                RTNIND: this.pagingDataList.length === 0 ? '' : 1,
                OPTION: 1,
                MPSTS: 0, // 查询条件
                PINFLAG: this.pinFlag,
                VALDATE: this.VALDATE,
                PURDATE: this.PURDATE,
                PURTIME: this.PURTIME,
                TRANNO: this.TRANNO,
            };
            const res_3076 = await get_3xxx(
                '3076',
                '灵活分期查询',
                appBody_3076,
                this,
            );
            console.log(res_3076);
            if (!res_3076) return false;
            const res = res_3076.body.appBody.dataList;
            const tableDatares = [];
            res.forEach((e, i) => {
                console.log(e.PURDATE, e.PURTIME);
                e.i = `${i + 1}`;
                e.PURDATE_1 = moment(`${e.PURDATE}`).format('YYYY-MM-DD');
                e.PURTIME_1 = getFormatDate(`${e.PURTIME}`, `${e.VALDATE}`, `${e.PURDATE1}`);
                // e.MPFLAG_1 = e.MPFLAG == 1 ? "已申请分期" : "无";
                if (e.MPFLAG != 1) {
                    e.MPFLAG_1 = '无';
                    tableDatares.push(e);
                }
            });

            this.tableData = tableDatares;
            this.showNimble00 = true;
            ChangePage(this, ['VALDATE', 'PURDATE', 'PURTIME', 'TRANNO'], 'tableData');
            this.isLoading = false;
        },
        // 申请
        async onChoice() {
            if (this.currentRow.MPFLAG == 1) return this.$message.warning('交易已被分期，不能重复申请!');
            const confirmResult = await this.$confirm(
                '此操作将对灵活分期申请, 您确认需要申请吗？',
                '灵活分期申请提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    customClass: 'warning', type: 'warning',
                },
            ).catch(err => err);
            if (confirmResult !== 'confirm') return this.$message.info('已取消灵活分期申请');

            await this.get_4072();
        },
        // 试算 4089
        async onChanger() {
            if (this.currentRow == null) return false;
            this.get_4089();
        },
        async get_4089() {
            this.isLoading = true;
            // 4089 配置请求头
            const appBody_4089 = {
                CARDNBR: this.nimbleForm.CARDNBR,
                OPT: 1,
                PINFLAG: this.pinFlag,
                CREDNO: this.nimbleForm.CREDNO,
                NBRMTHS: this.tryData[0].OUTFLAG || '', // 分期期数
                BILLAMT: setNumber(this.currentRow.AMOUNT, 12),
                CURRNUM: '156',
            };
            console.log(appBody_4089);
            const result_4089 = await get_3xxx(
                '4089',
                '灵活分期试算',
                appBody_4089,
                this,
            );
            console.log(result_4089);
            if (!result_4089) return false;
            // 成功之后当前显示
            this.isDisble = false;
            const feeInstl = result_4089.body.appBody.FEEINSTL; // 月手续费
            const instalAmt = result_4089.body.appBody.INSTALAMT; // 月还款额
            const feeAmt = result_4089.body.appBody.FEEAMT; // 总手续费
            const feePcnt = result_4089.body.appBody.FEEPCNT; // 利率
            const feeFlag = result_4089.body.appBody.FEEFLAG; // 0：一次性收取 1：分期收取
            const mp_irr = result_4089.body.appBody.MPIRR; // 年化利率
            const { NBRMTHS } = result_4089.body.appBody; // 分期期数

            const amount = this.currentRow.AMOUNT;
            const mon = parseInt(NBRMTHS);
            // 首期还款额 = 本金 / 期数 + 总手续费
            const firstAmts = amount / mon + feeAmt;

            // 总还款额 = 总手续费 + 本金
            const allcountfee = feeAmt + amount * 1;
            console.log(feeAmt, amount);

            // 本金 = 本金 / 期数
            let corpus = 0;
            corpus = amount / mon;
            // if (feeFlag == 0) {
            //   feeAmt = feeAmt * 0.75;
            //   firstAmts = (firstAmts - corpus) * 0.75 + corpus;
            //   allcountfee = allcountfee - feeAmt / 3;
            // }
            // 月还款额 = 本金 + 月手续费
            this.tryData[0].REMONTHFEE = ((corpus + feeInstl) * 1).toFixed(2);
            this.tryData[0].ALLCOUNTFEE = (allcountfee * 1).toFixed(2);
            // 首期还款额 = 本金 / 期数 + 总手续费
            this.tryData[0].CORPUS = (firstAmts * 1).toFixed(2);
            this.tryData[0].ALLMONTHSFEE = feeAmt.toFixed(2);
            // this.tryData[0].OUTFLAG = NBRMTHS
            this.tryData[0].MPIRR = mp_irr;
            console.log(
                feeInstl,
                instalAmt,
                feeAmt,
                feePcnt,
                feeFlag,
                mp_irr,
                NBRMTHS,
                amount,
                mon,
                firstAmts,
            );
            this.isLoading = false;
        },
        // 请求4072
        async get_4072() {
            this.isLoading = true;
            // 4072 配置请求头
            const appBody_4072 = {
                CARDNBR: this.nimbleForm.CARDNBR,
                OPTION: 1,
                OPERTP: 0,
                PINFLAG: this.pinFlag,
                CREDNO: this.nimbleForm.CREDNO,
                VALDATE: this.currentRow.VALDATE, // 原始交易入账日期
                PURDATE: this.currentRow.PURDATE, // 原始交易记录日期
                PURTIME: this.currentRow.PURTIME, // 原始交易消费时间
                TRANNO: this.currentRow.TRANNO, // 原始交易流水号
                TRANTP: this.currentRow.TRANTYPE, // 原始交易类型
                NBRMTHS: this.tryData[0].OUTFLAG || '', // 分期期数
                BILLAMT: setNumber(this.currentRow.AMOUNT, 12),
                CURRNUM: '156',
            };
            console.log(appBody_4072);
            const result_4072 = await get_4xxx(
                '4072',
                '灵活分期申请',
                appBody_4072,
                this,
            );
            console.log(result_4072);
            if (!result_4072) return false;
            // 成功之后当前显示

            this.showApplydaily = true;

            const res = result_4072.body.appBody;
            this.ApplyCashForm = [
                { keys: '分期期数 : ', values: res.MONTHNBR },
                { keys: '每月还款额 : ', values: res.INSTALAMT },
                { keys: '总手续费 : ', values: res.FEEAMT },
            ];
            // console.log(result_4094);
            // 发送新增分期申请记录 tbBudgetRequisi
            const tbBudgetRequisiData = JSON.parse(JSON.stringify(tbBudgetRequisi));
            tbBudgetRequisiData.agentid = this.defaultParams.body.appHead.opeNo;
            tbBudgetRequisiData.allcountfee = res.FEEAMT;
            tbBudgetRequisiData.banknum = this.defaultParams.body.appHead.bnknbr;
            tbBudgetRequisiData.budgettype = res.OPERTP;
            tbBudgetRequisiData.custid = this.cardInfo_3004.CUSTID || '无';
            tbBudgetRequisiData.custname = this.cardInfo_3004.NAME;
            tbBudgetRequisiData.custno = res.CARDNBR;
            tbBudgetRequisiData.instalamt = this.currentRow.AMOUNT;
            // tbBudgetRequisiData.jzrate = res.FEERATE
            tbBudgetRequisiData.planno = res.CREDNO;
            tbBudgetRequisiData.retcode = '000000';
            tbBudgetRequisiData.monthnbr = res.MONTHNBR;

            console.log(tbBudgetRequisiData);
            try {
                const resss = await this.$post.businessStatistics.addTbBudgetRe(tbBudgetRequisiData);
                console.log(resss);
            } catch (error) {
                console.warn(error);
            }


            // this.$alert(`灵活分期申请成功,请勿重复提交 !`, `灵活分期申请提示！`, {
            //   confirmButtonText: "确定",
            //   center: true,
            //   type: "success ",
            //   showClose: false
            // });
            // 修改之后重新查询,避免重复发送请求
            await this.qry();

            this.isLoading = false;
        },
        onShortcut() {
            this.$router.push('/businessSystem/unBillChecked');
        },
        close(data) {
            this.showApplydaily = data;
        },
        onMptransQuery() {
            // this.showNimble02 = !this.showNimble02;
            this.$router.push('/businessSystem/mptransqry');
        },
        handleCurrentChange(val) {
            this.currentRow = val;
            if (!val) return false;
            this.id = this.currentRow.i || '';
            this.onChanger();
        },
        // 上下页切换
        handleChangePage(type) {
            this.currentRow = null;
            this.id = '';
            if (type === 'pre') {
                // 切换到上一页
                if (this.currentPageIndex - 2 < 0) {
                    this.pagingDataList = []; // 清空缓存 申请编号 -> 相当于首次查询
                    this.VALDATE = '';
                    this.PURDATE = '';
                    this.PURTIME = '';
                    this.TRANNO = '';
                } else {
                    this.currentPageIndex = this.currentPageIndex - 2;
                    this.VALDATE = this.pagingDataList[this.currentPageIndex].VALDATE;
                    this.PURDATE = this.pagingDataList[this.currentPageIndex].PURDATE;
                    this.PURTIME = this.pagingDataList[this.currentPageIndex].PURTIME;
                    this.TRANNO = this.pagingDataList[this.currentPageIndex].TRANNO;
                }
                this.get_3076();
            } else {
                // 切换到下一页
                this.get_3076();
            }
        },
    },
};
</script>

<style  scoped lang="scss">
.nimble-contnair {
    /deep/.el-card__header {
        padding: 8px !important;
    }
    /deep/.form-row {
        width: 100%;
        margin: 0 auto;
        .el-form {
            //   text-align: left;
            margin: 0 auto;
            width: 500px;
            .el-form-item {
                text-align: center;
            }
        }
        .el-select {
            width: 100%;
            margin-bottom: 15px;
        }
    }

    .el-form-item {
        text-align: center;
    }
    .tab {
        width: 50%;
        border-collapse: collapse;
        margin: 0 auto;
        text-align: center;
        color: #303133;
        th {
            padding: 10px;
            background-color: #f5f7fa;
            border: 1px solid #dcdfe6;
        }
        td {
            width: 50%;
            padding: 5px;
            border: 1px solid #dcdfe6;
        }
        .heard {
            background-color: #f5f7fa;
            padding: 10px;
        }
    }
    .footer {
        text-align: center;
        margin-top: 10px;
    }
}
</style>
